package com.reading.cms.framework.shiro.service;

import com.reading.cms.exception.user.CaptchaException;
import com.reading.cms.exception.user.UserBlockedException;
import com.reading.cms.exception.user.UserNotExistsException;
import com.reading.cms.exception.user.UserPasswordNotMatchException;
import com.reading.cms.framework.constant.ShiroConstants;
import com.reading.cms.framework.constant.UserStatus;
import com.reading.cms.utils.IpUtils;
import com.reading.cms.utils.ServletUtil;
import com.reading.common.constant.UserConstants;
import com.reading.common.entity.system.SysUser;
import com.reading.common.entity.system.UserEventLog;
import com.reading.common.utils.DateUtil;
import com.reading.core.manager.system.IUserEventLogManager;
import com.reading.core.manager.system.ISystemUserManager;
import com.reading.core.utils.PasswordUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class LoginService {

    @Resource
    private ISystemUserManager userManager;

    @Resource
    private IUserEventLogManager userEventLogManager;

    /**
     * 登录
     */
    public SysUser login(String username, String password) {
        // 验证码校验
        if (!StringUtils.isEmpty(ServletUtil.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) {
            throw new CaptchaException();
        }
        //短信验证码校验
        if (!StringUtils.isEmpty(ServletUtil.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA_SMS))) {
            throw new CaptchaException();
        }

        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
            || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }

        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
            || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }

        // 查询用户信息
        SysUser sysUser = userManager.selectUserByLoginName(username);

        if (sysUser == null && maybeMobilePhoneNumber(username)) {
            sysUser = userManager.selectUserByPhoneNumber(username);
        }

        if (sysUser == null && maybeEmail(username)) {
            sysUser = userManager.selectUserByEmail(username);
        }

        if (sysUser == null || UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            throw new UserNotExistsException();
        }

        boolean isOK = PasswordUtil.matches(sysUser.getLoginName(), password, sysUser.getSalt(), sysUser.getPassword());
        if (!isOK) {
            throw new UserPasswordNotMatchException();
        }

        if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            throw new UserBlockedException(sysUser.getUserName());
        }
        recordLoginInfo(sysUser);
        return sysUser;
    }

    private boolean maybeEmail(String username) {
        if (!username.matches(UserConstants.EMAIL_PATTERN)) {
            return false;
        }
        return true;
    }

    private boolean maybeMobilePhoneNumber(String username) {
        if (!username.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN)) {
            return false;
        }
        return true;
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser sysUser) {
        String loginIP = IpUtils.getIpAddr(ServletUtil.getRequest());
//        String loginIP = ShiroUtil.getIp();

        sysUser.setLoginIp(loginIP);
        sysUser.setLoginDate(DateUtil.getNowDate());
        userManager.updateUser(sysUser);

        UserEventLog userEventLog = new UserEventLog();
        userEventLog.setUserId(sysUser.getUserId());
        userEventLog.setEventAddress(sysUser.getLoginIp());
        userEventLog.setEventType(1);
        userEventLog.setRemark("账号：" + sysUser.getLoginName() + "登陆,IP：" + loginIP);
        userEventLogManager.save(userEventLog);
    }

}
